package com.taptech.doufu.manager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taptech.doufu.app.MyActivityManager;
import com.taptech.doufu.db.userlog.UserLogDBUtil;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.bean.UserLogGsonBean;
import com.taptech.doufu.bean.UserLogModel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

public class UserLogManager {
    //事件名称
    public static final String LOG_EVENT_NAME_NOVEL_DETAIL = "goNovelCover";  //统计小说详情页面
    public static final String LOG_EVENT_NAME_BUY_FULL_NOVEL = "buyFullNovel";  //购买完本
    public static final String LOG_EVENT_NAME_NOVEL_COLLECT = "novelCollect";  //收藏小说
    public static final String LOG_EVENT_NAME_NOVEL_UN_COLLECT = "novelUnCollect";  //取消收藏小说
    public static final String LOG_EVENT_NAME_NOVEL_READ = "novelController";  //小说阅读页面
    public static final String LOG_EVENT_NAME_NOVEL_REWARD = "reward";  //打赏


    //一级页面
    public static final String LOG_EVENT_NAME_FIRST_PAGE_SEARCH = "search";  //搜索
    public static final String LOG_EVENT_NAME_FIRST_PAGE_BOOKSHELF = "bookShelf";  //书架
    public static final String LOG_EVENT_NAME_FIRST_PAGE_COMMUNITY = "community";  //社区
    public static final String LOG_EVENT_NAME_FIRST_PAGE_HOME = "home";  //首页
    public static final String LOG_EVENT_NAME_FIRST_PAGE_MESSAGE = "message";  //消息
    public static final String LOG_EVENT_NAME_FIRST_PAGE_MINE = "mine";  //我的
    public static final String LOG_EVENT_NAME_FIRST_PAGE_CHOICE = "choice";  //精选
    public static final String LOG_EVENT_NAME_FIRST_PAGE_ROMANCE = "romance";  //言情
    public static final String LOG_EVENT_NAME_FIRST_PAGE_RAINBOW = "rainbow";  //彩虹
    public static final String LOG_EVENT_NAME_FIRST_PAGE_RAINBOW_FINISHED = "rainbow_finished";  //彩虹
    public static final String LOG_EVENT_NAME_FIRST_PAGE_COMIC = "comic";  //漫画
    public static final String LOG_EVENT_NAME_FIRST_PAGE_COPYRIGHT= "copy_right";  //版权合作
    public static final String LOG_EVENT_NAME_FIRST_PAGE_TALK = "talk";  //对话小说
    public static final String LOG_EVENT_NAME_FIRST_PAGE_NEWVIP = "newVip";  //新会员
    public static final String LOG_EVENT_NAME_FIRST_PAGE_SAMEPERSON = "samePerson";  //同人

    public static final String LOG_EVENT_NAME_READ_TIME = "readTime";   //阅读时长


    public static final int UPLOAD_MAX_SIZE = 500;



    /**
     * 通用统计
     * @param eventName
     */
    public static void addLog(String eventName) {
        String curPageName = MyActivityManager.getInstance().getCurPageName();
        String prePageName = MyActivityManager.getInstance().getParentPageName();
        long time = System.currentTimeMillis();
        UserLogModel model = new UserLogModel(eventName, time, prePageName, curPageName);
        insertLog(model);
    }


    /**
     * 搜索
     * @param eventName
     * @param keyword
     */
    public static void addLogBySearch(String eventName, String keyword) {
        String curPageName = MyActivityManager.getInstance().getCurPageName();
        String prePageName = MyActivityManager.getInstance().getParentPageName();
        long time = System.currentTimeMillis();
        UserLogModel model = new UserLogModel(eventName, time, prePageName, curPageName);
        model.setKeyword(keyword);
        insertLog(model);
    }

    /**
     * 特殊统计  需要附加小说ID
     * @param eventName
     * @param novelID
     */
    public static void addLog(String eventName, String novelID) {
        String curPageName = MyActivityManager.getInstance().getCurPageName();
        String prePageName = MyActivityManager.getInstance().getParentPageName();
        long time = System.currentTimeMillis();
        UserLogModel model = new UserLogModel(eventName, time, prePageName, curPageName);
        model.setNovelID(novelID);
        insertLog(model);
    }

    /**
     * 特殊统计  需要统计从何处点击进入此页面
     * @param eventName
     * @param novelID
     * @param clickPlace
     */
    public static void addLog(String eventName,String novelID,String clickPlace){
        String curPageName = MyActivityManager.getInstance().getCurPageName();
        String prePageName = MyActivityManager.getInstance().getParentPageName();
        long time = System.currentTimeMillis();
        UserLogModel model = new UserLogModel(eventName, time, prePageName, curPageName);
        model.setNovelID(novelID);
        model.setClickPlace(clickPlace);
        insertLog(model);
    }

    /**
     * 特殊统计  需要统计从何处点击进入此页面
     * @param eventName 事件名称
     * @param novelID   小说ID
     * @param clickPlace 点击的地方
     * @param prePageName  上一个页面
     */
    public static void addLog(String eventName,String novelID,String clickPlace,String prePageName,String curPageName){
        long time = System.currentTimeMillis();
        UserLogModel model = new UserLogModel(eventName, time, prePageName, curPageName);
        model.setNovelID(novelID);
        model.setClickPlace(clickPlace);
        insertLog(model);
    }

    /**
     * 特殊统计 统计每次阅读小说的时长
     * @param eventName
     * @param novelID
     * @param readTime
     */
    public static void addLog(String eventName, String novelID, long readTime) {
        String curPageName = MyActivityManager.getInstance().getCurPageName();
        String prePageName = MyActivityManager.getInstance().getParentPageName();
        long time = System.currentTimeMillis();
        UserLogModel model = new UserLogModel(eventName, time, prePageName, curPageName);
        model.setNovelID(novelID);
        model.setReadTime(readTime);
        insertLog(model);
    }


    private static void insertLog(final UserLogModel model) {
        Observable.create(new Observable.OnSubscribe<Long>() {
            @Override
            public void call(Subscriber<? super Long> subscriber) {
                long id = UserLogDBUtil.getInstance().insertLog(model);
                subscriber.onNext(id);
            }
        }).compose(RxJavaHelper.<Long>observeOnMainThread())
        .subscribe(new BaseSubscriber<Long>(){
            @Override
            public void onNext(Long aLong) {
                super.onNext(aLong);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }


    private static JSONArray listToJSONArray(List<UserLogModel> list) {
        JSONArray array = new JSONArray();
        for(UserLogModel model:list){
            if (model == null) {
                continue;
            }
            JSONObject data = new JSONObject();
            data.put("curPage", model.getCurPage());
            data.put("prePage", model.getPrePage());
            data.put("date", model.getTime());
            data.put("eventName", model.getEventName());
            data.put("uid", model.getUid());
            JSONObject otherInfo = new JSONObject();
            otherInfo.put("novelID", model.getNovelID());
            otherInfo.put("clickPlace", model.getClickPlace());
            otherInfo.put("readTime", model.getReadTime());
            otherInfo.put("keyword",model.getKeyword());
            data.put("otherInfo", otherInfo);
            array.add(data);
        }
        return array;
    }


    public static void uploadLocalLogs(){
        //处理本地数据
        Observable.create(new Observable.OnSubscribe<Map<String, Object>>() {
                @Override
                public void call(Subscriber<? super Map<String, Object>> subscriber) {

                    final List<UserLogModel> list = UserLogDBUtil.getInstance().getList(UPLOAD_MAX_SIZE);
                    if (list==null || list.size()==0){
                        return;
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("array", listToJSONArray(list));
                    map.put("list", list);
                    subscriber.onNext(map);
                }
                }).compose(RxJavaHelper.<Map<String, Object>>observeOnMainThread())
                .subscribe(new BaseSubscriber<Map<String, Object>>(){
                    @Override
                    public void onNext(Map<String, Object> logModels) {
                        super.onNext(logModels);
                        if (logModels == null) return;
                        try {
                            JSONArray array = (JSONArray) logModels.get("array");
                            List<UserLogModel> list = (List<UserLogModel>) logModels.get("list");
                            uploadData(array,list);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });

    }

    /**
     * 上传数据
     * @param array
     * @param list
     */
    private static void uploadData(JSONArray array,final List<UserLogModel> list) {
        ApiClient.getInstance().apiService.uploadUserLog(array.toJSONString())
                .map(new Func1<UserLogGsonBean, UserLogGsonBean>() {

                    @Override
                    public UserLogGsonBean call(UserLogGsonBean responseBaseBean) {
                        if (responseBaseBean != null && responseBaseBean.getData() != null
                                && responseBaseBean.getData().getSuccess() == 1) {
                            UserLogDBUtil.getInstance().delete(list);
                            return responseBaseBean;
                        }else{
                            return null;
                        }
                    }
                })
                .compose(RxJavaHelper.<UserLogGsonBean>observeOnMainThread())
                .subscribe(new BaseSubscriber<UserLogGsonBean>(){
                    @Override
                    public void onNext(UserLogGsonBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                        if (responseBaseBean != null && list.size() >= UPLOAD_MAX_SIZE) {
                            uploadLocalLogs();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });

    }




}
